<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\adminapi\logic\promotion;


use app\common\model\app\App;
use app\common\model\bookpack\Bookpack;
use app\common\model\click\BdClick;
use app\common\model\click\KsClick;
use app\common\model\click\UcClick;
use app\common\model\click\VivoClick;
use app\common\model\media\Media;
use app\common\model\media\MediaAccount;
use app\common\model\promotion\PromotionLink;
use app\common\logic\BaseLogic;
use app\common\model\recharge_template\RechargeTemplate;
use app\common\model\return_rule\ReturnRule;
use app\common\model\skits\Skits;
use app\common\model\skits\SkitsEpisodes;
use app\common\service\media\MediaService;
use think\facade\Db;


/**
 * PromotionLink逻辑
 * Class PromotionLinkLogic
 * @package app\adminapi\logic
 */
class PromotionLinkLogic extends BaseLogic
{


    /**
     * 添加推广链
     *
     * @param array $params
     * @return bool|string
     */
    public static function add(array $params)
    {
        if (!$appId = $params['app_id'] ?? 0) {

            return '请选择推广应用';
        }

        Db::startTrans();
        try {
            $result = PromotionLink::create([
                'app_id'               => $appId,
                'admin_id'             => $params['admin_id'],
                'name'                 => $params['name'],
                'k_coin'               => $params['k_coin'],
                'recharge_template_id' => $params['recharge_template_id'] ?? 0,
                'skits_id'             => $params['skits_id'],
                'episodes_id'          => $params['episodes_id'],
                'skits_name'           => $params['skits_name'],
                'episodes_name'        => $params['episodes_name'],
                'media_id'             => $params['media_id'],
                'remark'               => $params['remark'] ?? '',
                'audit_mode'           => $params['audit_mode'] ?? 0,
                'media_feedback'       => $params['media_feedback'] ?? 1,
            ]);
            $app    = App::where('id', $params['app_id'])->findOrEmpty();
            $data   = self::getUrl($result->id, $app, $params['skits_id'], $params['episodes_id'], $params['media_id']);
            PromotionLink::where('id', $result->id)->update($data);

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * 获取推广链接
     *
     * @param $linkId
     * @param $media
     * @param $packageName
     * @param $params
     * @return array
     */
    public static function getUrl($linkId, $app, $skitsId, $episodesId, $mediaId)
    {
        $skits    = Skits::find($skitsId);
        $episodes = SkitsEpisodes::find($episodesId);

        $uri = 'skits_id=' . $skitsId . '&episodes_id=' . $episodesId . '&promotion_link_id=' . $linkId . '&media=' . $mediaId;
        switch ($app->channel) {
            case 1 :
                $uri .= '&douyin_drama_id=' . $skits->douyin_drama_id . '&douyin_episodes_id=' . $episodes->douyin_episodes_id;
                break;
            case 2:
                $uri .= '&wechat_drama_id=' . $skits->wechat_drama_id . '&wechat_episodes_id=' . $episodes->wechat_media_id;
                break;
        }
        $httpUrl = $app->http_url;
        $httpUrl .= '?' . $uri;

        switch ($mediaId) {
            case Media::SOURCE_JL :
                return [
                    'http_url'        => $httpUrl,
                    'custom_http_url' => config('project.jl_monitoring_link') . '&' . $uri,
                ];
            case Media::SOURCE_UC :
                return [
                    'http_url'        => $httpUrl,
                    'custom_http_url' => config('project.uc_monitoring_link') . '&' . $uri,
                ];
            case Media::SOURCE_KS :
                return [
                    'http_url'        => $httpUrl . '&callback=__CALLBACK__',
                    'custom_http_url' => config('project.ks_monitoring_link') . '&' . $uri,
                ];
            default :
                return [];
        }
    }


    /**
     * @notes 编辑
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/03/04 19:26
     */
    public static function edit(array $params): bool
    {
        Db::startTrans();
        try {
            PromotionLink::where('id', $params['id'])->update([
                'k_coin'               => $params['k_coin'],
                'recharge_template_id' => $params['recharge_template_id'],
                'remark'               => $params['remark'] ?? '',
                'audit_mode'           => $params['audit_mode'],
                'media_feedback'       => $params['media_feedback'],
            ]);

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * @notes 删除
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/03/04 19:26
     */
    public static function delete(array $params): bool
    {
        return PromotionLink::destroy($params['id']);
    }


    /**
     * @notes 获取详情
     * @param $params
     * @return array
     * @author likeadmin
     * @date 2024/03/04 19:26
     */
    public static function detail($params): array
    {
        $result = PromotionLink::findOrEmpty($params['id'])->toArray();
        // type=1 复制推广链
        $type = $params['type'] ?? 0;
        if ($type == 1) {
            $returnRule = ReturnRule::where('promotion_link_id', $params['id'])->findOrEmpty();
            if ($returnRule->isEmpty()) {
                self::setError('请先绑定回传规则');
                return [];
            }
            // $mediaAccount = MediaAccount::where('promotion_link_id', $params['id'])->findOrEmpty();
            // if ($mediaAccount->isEmpty()) {
            //     self::setError('请先绑定媒体账户');
            //     return [];
            // }
        }

        $result['recharge_template_name'] = RechargeTemplate::where('id', $result['recharge_template_id'])->value('name') ?? '';

        return $result;
    }


    /**
     * 联调测试
     *
     * @param $id
     * @param $type
     * @return bool
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function joinTest($id, $type)
    {
        if (!$id || !$type) {

            return false;
        }

        $link = PromotionLink::where('id', $id)->findOrEmpty();
        if ($link->isEmpty()) {

            return false;
        }
        $media = $link->media;
        switch ($media) {
            case Media::SOURCE_BD :
                $click = BdClick::where('promotion_link_id', $id)->order('id', 'desc')->findOrEmpty();
                if ($click->isEmpty()) {

                    return false;
                }
                $callback = $click->callback_url ?? '';
                if (!$callback) {

                    return false;
                }
                $isReturn = false;
                if ($click->oaid && $click->oaid != 'NULL' && $click->oaid != '__OAID__') {
                    $joiType  = 'oaid';
                    $isReturn = true;
                }
                if ($click->imei_md5 && $click->imei_md5 != 'NULL' && $click->imei_md5 != '__IMEI_MD5__') {
                    $joiType  = 'imei';
                    $isReturn = true;
                }
                if ($click->ip && $click->ip != '__IP__') {
                    $joiType  = 'ip';
                    $isReturn = true;
                }
                if ($isReturn) {
                    if ($type == 1) {
                        MediaService::BdReturn(['user_id' => '百度应用调起联调测试'], $joiType, $click->callback_url, MediaService::BD_TYPE_DEEPLINK);
                        return MediaService::BdReturn(['user_id' => '百度激活联调测试'], $joiType, $click->callback_url, MediaService::BD_TYPE_ACTIVE);
                    }
                    if ($type == 2) {
                        return MediaService::BdReturn(['user_id' => '百度加桌联调测试'], $joiType, $click->callback_url, MediaService::BD_TYPE_ADD_DESKTOP);
                    }
                    if ($type == 3) {
                        return MediaService::BdReturn(['user_id' => '百度付费联调测试'], $joiType, $click->callback_url, MediaService::BD_TYPE_PAYMENT);
                    }
                    if ($type == 4) {
                        return MediaService::BdReturn(['user_id' => '百度关键行为联调测试'], $joiType, $click->callback_url, MediaService::BD_TYPE_ACTION);
                    }
                }
                return false;
            case Media::SOURCE_KS :
                $click = KsClick::where('promotion_link_id', $id)->order('id', 'desc')->findOrEmpty();
                if ($click->isEmpty()) {

                    return false;
                }
                $callback = $click->callback ?? '';
                if (!$callback) {

                    return false;
                }
                if ($type == 1) {
                    return MediaService::KsReturn(['user_id' => '快手激活联调测试'], $callback, MediaService::KS_TYPE_ACTIVE);
                }
                if ($type == 2) {
                    return MediaService::KsReturn(['user_id' => '快手加桌联调测试'], $callback, MediaService::KS_TYPE_REGISTER);
                }
                if ($type == 3) {
                    return MediaService::KsReturn(['user_id' => '快手付费联调测试'], $callback, MediaService::KS_TYPE_PAYMENT, 10);
                }
                if ($type == 4) {
                    return MediaService::KsReturn(['user_id' => '快手关键行为联调测试'], $callback, MediaService::KS_TYPE_PAYMENT);
                }
                return false;
            case Media::SOURCE_UC :
                $click = UcClick::where('promotion_link_id', $id)->order('id', 'desc')->findOrEmpty();
                if ($click->isEmpty()) {

                    return false;
                }
                $callback = $click->callback_url ?? '';
                if ($type == 1) {
                    return MediaService::UcReturn(['user_id' => 'UC激活联调测试'], $callback, MediaService::UC_TYPE_ACTIVE);
                }
                if ($type == 2) {
                    return MediaService::UcReturn(['user_id' => 'UC加桌联调测试'], $callback, MediaService::UC_TYPE_ADD_DESKTOP);
                }
                if ($type == 3) {
                    MediaService::UcReturn(['user_id' => 'UC快应用付费联调测试'], $callback, MediaService::UC_TYPE_PAYMENT);
                    return MediaService::UcReturn(['user_id' => 'UC付费联调测试'], $callback, MediaService::UC_TYPE_PAY);
                }
                return false;
            case Media::SOURCE_VIVO :
                $click = VivoClick::where('promotion_link_id', $id)->order('id', 'desc')->findOrEmpty();
                if ($click->isEmpty()) {

                    return false;
                }
                if ($type == 1) {
                    return MediaService::VivoReturn(['user_id' => 'VIVO激活联调测试'], $click, MediaService::VIVO_TYPE_ACTIVE);
                }
                if ($type == 2) {
                    return MediaService::VivoReturn(['user_id' => 'VIVO加桌联调测试'], $click, MediaService::VIVO_TYPE_ADD_DESKTOP);
                }
                if ($type == 3) {
                    return MediaService::VivoReturn(['user_id' => 'VIVO付费联调测试'], $click, MediaService::VIVO_TYPE_PAYMENT, 10);
                }
            default:
                return false;
        }
    }
}
